package com.cap.bts.framework.auth.login;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.cap.bts.commonfunc.common.constant.OperationType;
import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.framework.auth.filter.SSOAuthInterceptor;
import com.cap.bts.framework.auth.util.UserAuthenticationUtils;
import com.cap.bts.framework.bizlog.domain.BizLog;
import com.cap.bts.framework.bizlog.service.IBizLoggerService;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.usermgnt.domain.User;
import com.cap.bts.framework.usermgnt.service.IUserMgntService;
import com.cap.bts.framework.workbench.constant.WorkbenchConstant;

@Component
public class UserAutoLogin {
	private static Logger logger = Logger.getLogger(UserAutoLogin.class);
	@Autowired
	private IUserMgntService userService;
	@Autowired
	private IBizLoggerService bizloggerService;

	public boolean login(HttpServletRequest request, HttpServletResponse response,
			String userCode, boolean isSelectOrgs) throws AppException {
		String URL = (String) request.getSession().getAttribute(
				WorkbenchConstant.PREVIOUS_URL);

		// if session store the uri string,forward to the uri
		if (StringUtils.isNotBlank(URL)) {
			request.setAttribute("contentUrl", URL);
			request.getSession()
					.removeAttribute(WorkbenchConstant.PREVIOUS_URL);

		} else {
			request.setAttribute("contentUrl", "content");
		}
		// If different user login in one session, expire the previous one.
		// UserAuthenticationUtils.checkDiffUserInOneSession(request,
		// actualUser.getUserCode());
		// Get new session
		// request.getSession(true).setAttribute("userSession", actualUser);

		User actualUser = null;
		actualUser = userService.getUserByUserCode(userCode);

		if (isSelectOrgs || null == request.getSession(true).getAttribute("userSession")) {
			request.getSession(true).setAttribute("userSession", actualUser);
			
			
			
		} else {
			User user = (User) request.getSession(true).getAttribute(
					"userSession");
			if (!user.getUserCode().equals(userCode)) {

				// result.rejectValue("errorMsg",
				// WorkbenchConstant.EXIST_USER_ACCOUNT);
				// return WorkbenchConstant.LOGIN_PAGE;
				return false;
			}
		}

		UserAuthenticationUtils.setLoginToCookie(request, response,
				actualUser.getUserCode());//--
		// Store Current Login user
		UserUtil.setCurrentUser(actualUser);

		if (actualUser != null) {
			try {
				BizLog userLog = new BizLog();
				userLog.setUserName(actualUser.getUserCode());
				userLog.setOperationType(OperationType.SSO_LOGIN_OPERATION
						.getValue());
				userLog.setOperationDesc(actualUser.getUserCode() + " "
						+ OperationType.SSO_LOGIN_OPERATION_MESSAGE.getValue());
				userLog.setOperationTime(new Date());
				userLog.setCreateBy(actualUser.getId());
				bizloggerService.log(userLog);
			} catch (Exception e) {
				logger.error(e);
			}
		}
		
		/**
		 * If this user has login in on another client, force invalid the
		 * session on another client. Added by GuYiFeng
		 */
		UserAuthenticationUtils.setSessionIdToCookie(request, response);//--
		UserAuthenticationUtils.checkLoginUserSession(request,
				actualUser.getUserCode());//--
		return true;
	}
}
